class EventsController < ApplicationController
   before_filter :check_authentication, :only => [:edit, :delete, :update]
  # GET /events
  # GET /events.xml
  def index
	#@events = Event.all
	@events = TypeEvent.find(:all,
						:joins => "INNER JOIN events ON type_events.id = events.type_event_id
								  INNER JOIN computers ON computers.id = events.computer_id
								  INNER JOIN rooms ON rooms.id = computers.room_id",
						:from => "type_events",
						:order => "events.created_at DESC",
						:select => "rooms.name as room_name, type_events.name as type_event, computers.name as computer_name, computers.id as computer_id, events.id as event_id, events.updated_at as date_resolution, events.created_at as date_creation, events.information as event_info, events.state as state_event "
						)
	#puts YAML::dump(@events)

	respond_to do |format|
	  format.html # index.html.erb
	  format.xml  { render :xml => @events }
	end
  end
  

  # GET /events/1
  # GET /events/1.xml
  def show
  	begin
		@event = Event.find(params[:id])
	rescue
		@error = true
	end
	respond_to do |format|
	  format.html # show.html.erb
	  format.xml  { render :xml => @event }
	end
  end

  # GET /events/new
  # GET /events/new.xml
  def new
	@event = Event.new

	respond_to do |format|
	  format.html # new.html.erb
	  format.xml  { render :xml => @event }
	end
  end

  # GET /events/1/edit
  def edit
  	begin
		@event = Event.find(params[:id])
	rescue
		@error = true
	end
  end

  # POST /events
  # POST /events.xml
  def create
	@event = Event.new(params[:event])

	respond_to do |format|
	  if @event.save
		flash[:notice] = 'Un évènement a été créé.'
		format.html { redirect_to(@event) }
		format.xml  { render :xml => @event, :status => :created, :location => @event }
	  else
		format.html { render :action => "new" }
		format.xml  { render :xml => @event.errors, :status => :unprocessable_entity }
	  end
	end
  end

  # PUT /events/1
  # PUT /events/1.xml
  def update
	@event = Event.find(params[:id])

	respond_to do |format|
	  if @event.update_attributes(params[:event])
		flash[:notice] = 'Un évènement a bien été modifié.'
		format.html { redirect_to(@event) }
		format.xml  { head :ok }
	  else
		format.html { render :action => "edit" }
		format.xml  { render :xml => @event.errors, :status => :unprocessable_entity }
	  end
	end
  end

  # DELETE /events/1
  # DELETE /events/1.xml
  def destroy
	@event = Event.find(params[:id])
	@event.destroy

	respond_to do |format|
	  format.html { redirect_to(events_url) }
	  format.xml  { head :ok }
	end
  end
  def raise_incident
	incidents = Event.find(:all, :conditions => ["created_at > ?", 5.minutes.ago])

	#if incidents.size > 0
	  	#Mailer.deliver_events_append()
	#end
   
	render :text => "#{incidents.size} Incident(s) détecté!"

  end
end
